#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <cstring>
#include <memory>

#include "Log.hpp"
#include "Common.hpp"

static uint16_t gport = 8081;

#define BACKLOG 8

using namespace LogModule;

class TcpServer
{
public:
    TcpServer(int port = gport) : _port(port), _isrunning(false)
    {
    }

    void InitServer()
    {
        // 1. 套接字创建(流式套接字 -- socket stream)
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket create success, sockfd is : " << _listensockfd;
        // 对象填充
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(gport);
        local.sin_addr.s_addr = INADDR_ANY;
        // 2. bind
        int n = ::bind(_listensockfd, CONV(&local), sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd is : " << _listensockfd;

        // 3. cs, tcp是面向连接的，就需要tcp随时地等待被连接
        //   tcp需要将socket设置为监听状态
        n = ::listen(_listensockfd, BACKLOG);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd is : " << _listensockfd;
    }
    void HandlerRequest(int sockfd)
    { // TCP也是全双工的
        LOG(LogLevel::INFO) << "HandlerRequest, new sockfd is : " << sockfd;
        // TCP面向字节流，和文件更类似
        char inbuffer[4096];
        while (true)
        {
            ssize_t n = ::read(sockfd, inbuffer, sizeof(inbuffer) - 1);
            if (n > 0)
            {
                LOG(LogLevel::INFO) << inbuffer;

                inbuffer[n] = 0;
                std::string echo_str = "Server echo# ";
                echo_str += inbuffer;

                ::write(sockfd, echo_str.c_str(), echo_str.size());
            }
        }
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 不能直接读取数据，需要获取新连接：
            struct sockaddr_in peer;
            socklen_t peerlen;
            int sockfd = ::accept(_listensockfd, CONV(&peer), &peerlen);
            if (sockfd < 0)
            {
                // sockfd，表示获取未成功，重新获取其他的新连接
                LOG(LogLevel::WARNING) << "accept error : " << strerror(errno);
                continue;
            }

            // 获取成功：
            LOG(LogLevel::INFO) << "listen success, new sockfd is : " << sockfd;

            //  version - 0
            HandlerRequest(sockfd);
        }
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;
};
